<template>
  <div class="system-config-container">
    <el-row :gutter="20">
      <!-- 基础配置 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>基础配置</span>
          </template>
          <el-form
            ref="basicFormRef"
            :model="basicConfig"
            :rules="basicRules"
            label-width="120px"
            style="max-width: 800px"
          >
            <el-form-item label="网站名称" prop="siteName">
              <el-input v-model="basicConfig.siteName" placeholder="请输入网站名称" />
            </el-form-item>
            <el-form-item label="网站描述" prop="siteDescription">
              <el-input
                v-model="basicConfig.siteDescription"
                type="textarea"
                :rows="3"
                placeholder="请输入网站描述"
              />
            </el-form-item>
            <el-form-item label="网站关键词" prop="siteKeywords">
              <el-input v-model="basicConfig.siteKeywords" placeholder="请输入网站关键词，用逗号分隔" />
            </el-form-item>
            <el-form-item label="网站Logo" prop="siteLogo">
              <el-upload
                class="logo-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeLogoUpload"
                :http-request="handleLogoUpload"
              >
                <img v-if="basicConfig.siteLogo" :src="basicConfig.siteLogo" class="logo-image" />
                <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="ICP备案号" prop="icpNumber">
              <el-input v-model="basicConfig.icpNumber" placeholder="请输入ICP备案号" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicConfig" :loading="basicLoading">
                保存基础配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 邮件配置 -->
      <el-col :span="24" style="margin-top: 20px">
        <el-card>
          <template #header>
            <span>邮件配置</span>
          </template>
          <el-form
            ref="emailFormRef"
            :model="emailConfig"
            :rules="emailRules"
            label-width="120px"
            style="max-width: 800px"
          >
            <el-form-item label="SMTP服务器" prop="smtpHost">
              <el-input v-model="emailConfig.smtpHost" placeholder="请输入SMTP服务器地址" />
            </el-form-item>
            <el-form-item label="SMTP端口" prop="smtpPort">
              <el-input-number v-model="emailConfig.smtpPort" :min="1" :max="65535" />
            </el-form-item>
            <el-form-item label="发件人邮箱" prop="fromEmail">
              <el-input v-model="emailConfig.fromEmail" placeholder="请输入发件人邮箱" />
            </el-form-item>
            <el-form-item label="邮箱密码" prop="emailPassword">
              <el-input
                v-model="emailConfig.emailPassword"
                type="password"
                placeholder="请输入邮箱密码或授权码"
                show-password
              />
            </el-form-item>
            <el-form-item label="启用SSL" prop="enableSsl">
              <el-switch v-model="emailConfig.enableSsl" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveEmailConfig" :loading="emailLoading">
                保存邮件配置
              </el-button>
              <el-button @click="testEmail" :loading="testEmailLoading">
                测试邮件
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 存储配置 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>存储配置</span>
          </template>
          <el-form
            ref="storageFormRef"
            :model="storageConfig"
            :rules="storageRules"
            label-width="120px"
            style="max-width: 800px"
          >
            <el-form-item label="存储类型" prop="storageType">
              <el-radio-group v-model="storageConfig.storageType">
                <el-radio label="local">本地存储</el-radio>
                <el-radio label="oss">阿里云OSS</el-radio>
                <el-radio label="qiniu">七牛云</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <template v-if="storageConfig.storageType === 'oss'">
              <el-form-item label="AccessKey ID" prop="ossAccessKeyId">
                <el-input v-model="storageConfig.ossAccessKeyId" placeholder="请输入AccessKey ID" />
              </el-form-item>
              <el-form-item label="AccessKey Secret" prop="ossAccessKeySecret">
                <el-input
                  v-model="storageConfig.ossAccessKeySecret"
                  type="password"
                  placeholder="请输入AccessKey Secret"
                  show-password
                />
              </el-form-item>
              <el-form-item label="Bucket名称" prop="ossBucket">
                <el-input v-model="storageConfig.ossBucket" placeholder="请输入Bucket名称" />
              </el-form-item>
              <el-form-item label="地域节点" prop="ossEndpoint">
                <el-input v-model="storageConfig.ossEndpoint" placeholder="请输入地域节点" />
              </el-form-item>
            </template>

            <template v-if="storageConfig.storageType === 'qiniu'">
              <el-form-item label="AccessKey" prop="qiniuAccessKey">
                <el-input v-model="storageConfig.qiniuAccessKey" placeholder="请输入AccessKey" />
              </el-form-item>
              <el-form-item label="SecretKey" prop="qiniuSecretKey">
                <el-input
                  v-model="storageConfig.qiniuSecretKey"
                  type="password"
                  placeholder="请输入SecretKey"
                  show-password
                />
              </el-form-item>
              <el-form-item label="存储空间" prop="qiniuBucket">
                <el-input v-model="storageConfig.qiniuBucket" placeholder="请输入存储空间名称" />
              </el-form-item>
              <el-form-item label="访问域名" prop="qiniuDomain">
                <el-input v-model="storageConfig.qiniuDomain" placeholder="请输入访问域名" />
              </el-form-item>
            </template>

            <el-form-item>
              <el-button type="primary" @click="saveStorageConfig" :loading="storageLoading">
                保存存储配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 支付配置 -->
      <el-col :span="24" style="margin-top: 20px">
        <el-card>
          <template #header>
            <span>支付配置</span>
          </template>
          <el-form
            ref="paymentFormRef"
            :model="paymentConfig"
            :rules="paymentRules"
            label-width="120px"
            style="max-width: 800px"
          >
            <el-form-item label="支付宝AppId" prop="alipayAppId">
              <el-input v-model="paymentConfig.alipayAppId" placeholder="请输入支付宝AppId" />
            </el-form-item>
            <el-form-item label="支付宝私钥" prop="alipayPrivateKey">
              <el-input
                v-model="paymentConfig.alipayPrivateKey"
                type="textarea"
                :rows="3"
                placeholder="请输入支付宝应用私钥"
              />
            </el-form-item>
            <el-form-item label="支付宝公钥" prop="alipayPublicKey">
              <el-input
                v-model="paymentConfig.alipayPublicKey"
                type="textarea"
                :rows="3"
                placeholder="请输入支付宝公钥"
              />
            </el-form-item>
            <el-form-item label="微信AppId" prop="wechatAppId">
              <el-input v-model="paymentConfig.wechatAppId" placeholder="请输入微信AppId" />
            </el-form-item>
            <el-form-item label="微信商户号" prop="wechatMchId">
              <el-input v-model="paymentConfig.wechatMchId" placeholder="请输入微信商户号" />
            </el-form-item>
            <el-form-item label="微信密钥" prop="wechatKey">
              <el-input
                v-model="paymentConfig.wechatKey"
                type="password"
                placeholder="请输入微信支付密钥"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="savePaymentConfig" :loading="paymentLoading">
                保存支付配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { validEmail } from '@/utils/validate'

// 表单引用
const basicFormRef = ref(null)
const emailFormRef = ref(null)
const storageFormRef = ref(null)
const paymentFormRef = ref(null)

// 加载状态
const basicLoading = ref(false)
const emailLoading = ref(false)
const testEmailLoading = ref(false)
const storageLoading = ref(false)
const paymentLoading = ref(false)

// 基础配置
const basicConfig = reactive({
  siteName: '精进坊',
  siteDescription: '专注于个人成长和技能提升的学习平台',
  siteKeywords: '学习,成长,认知,健身,技能提升',
  siteLogo: '',
  icpNumber: ''
})

// 邮件配置
const emailConfig = reactive({
  smtpHost: '',
  smtpPort: 587,
  fromEmail: '',
  emailPassword: '',
  enableSsl: true
})

// 存储配置
const storageConfig = reactive({
  storageType: 'local',
  ossAccessKeyId: '',
  ossAccessKeySecret: '',
  ossBucket: '',
  ossEndpoint: '',
  qiniuAccessKey: '',
  qiniuSecretKey: '',
  qiniuBucket: '',
  qiniuDomain: ''
})

// 支付配置
const paymentConfig = reactive({
  alipayAppId: '',
  alipayPrivateKey: '',
  alipayPublicKey: '',
  wechatAppId: '',
  wechatMchId: '',
  wechatKey: ''
})

// 验证规则
const basicRules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' }
  ],
  siteDescription: [
    { required: true, message: '请输入网站描述', trigger: 'blur' }
  ]
}

const emailRules = {
  smtpHost: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  fromEmail: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  emailPassword: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ]
}

const storageRules = {
  storageType: [
    { required: true, message: '请选择存储类型', trigger: 'change' }
  ]
}

const paymentRules = {}

// 生命周期
onMounted(() => {
  loadConfigs()
})

// 加载配置
const loadConfigs = async () => {
  try {
    // 模拟加载配置数据
    setTimeout(() => {
      // 这里应该从后端API加载实际配置
      console.log('配置加载完成')
    }, 500)
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

// Logo上传前验证
const beforeLogoUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('Logo只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理Logo上传
const handleLogoUpload = (options) => {
  // 模拟上传
  const reader = new FileReader()
  reader.onload = (e) => {
    basicConfig.siteLogo = e.target.result
    ElMessage.success('Logo上传成功')
  }
  reader.readAsDataURL(options.file)
}

// 保存基础配置
const saveBasicConfig = () => {
  basicFormRef.value.validate((valid) => {
    if (valid) {
      basicLoading.value = true
      // 模拟保存操作
      setTimeout(() => {
        ElMessage.success('基础配置保存成功')
        basicLoading.value = false
      }, 1000)
    }
  })
}

// 保存邮件配置
const saveEmailConfig = () => {
  emailFormRef.value.validate((valid) => {
    if (valid) {
      emailLoading.value = true
      // 模拟保存操作
      setTimeout(() => {
        ElMessage.success('邮件配置保存成功')
        emailLoading.value = false
      }, 1000)
    }
  })
}

// 测试邮件
const testEmail = () => {
  emailFormRef.value.validate((valid) => {
    if (valid) {
      testEmailLoading.value = true
      // 模拟测试邮件
      setTimeout(() => {
        ElMessage.success('测试邮件发送成功')
        testEmailLoading.value = false
      }, 2000)
    }
  })
}

// 保存存储配置
const saveStorageConfig = () => {
  storageFormRef.value.validate((valid) => {
    if (valid) {
      storageLoading.value = true
      // 模拟保存操作
      setTimeout(() => {
        ElMessage.success('存储配置保存成功')
        storageLoading.value = false
      }, 1000)
    }
  })
}

// 保存支付配置
const savePaymentConfig = () => {
  paymentFormRef.value.validate((valid) => {
    if (valid) {
      paymentLoading.value = true
      // 模拟保存操作
      setTimeout(() => {
        ElMessage.success('支付配置保存成功')
        paymentLoading.value = false
      }, 1000)
    }
  })
}
</script>

<style scoped>
.system-config-container {
  padding: 20px;
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}

.logo-image {
  width: 100px;
  height: 60px;
  display: block;
  object-fit: contain;
}
</style>